package org.bdware.doip.core.model.metadata;

import org.apache.log4j.Logger;

import java.util.LinkedList;
import java.util.List;

public class SearchParameter{
    public String query;
    public int pageNum;
    public int pageSize;
    public List<SortField> sortFields;
    public String sortFieldsSer;
    public String type;
    Logger logger = Logger.getLogger(SearchParameter.class);

    public SearchParameter(String query, int pageNum, int pageSize, String sortFields, String type) {
        List<SortField> sortFieldList = new LinkedList<>();
        String[] sortFieldRes = sortFields.split(",");
        for (String sortField:sortFieldRes) {
            logger.debug("sort field: " + sortField);
            String[] tmpRes = sortField.split(":");
            if (tmpRes.length != 1 && tmpRes.length != 2) {
                logger.debug("wrong sort fields");
                continue;
            } else {
                if (tmpRes[0].equals("")) {
                    logger.debug("sort field is empty, ignore");
                    continue;
                }
            }

            SortField tmp = new SortField();
            tmp.item = tmpRes[0];
            if (tmpRes.length == 1) {
                logger.warn("no asc or desc specified, use asc for default");
                tmp.order = "ASC";
            } else {
                if (tmpRes[1].equals("")) {
                    logger.warn("no asc or desc specified, use asc for default");
                    tmp.order = "ASC";
                } else {
                    tmp.order = tmpRes[1];
                }
            }
            logger.debug("item: " + tmp.item);
            logger.debug("order: " + tmp.order);
            sortFieldList.add(tmp);
        }

        logger.debug("sort field size: " + sortFieldList.size());

        this.query = query;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.sortFields = sortFieldList;
        this.type = type;
        this.sortFieldsSer = sortFields;
    }

    public static SearchParameter getDefaultParameter(){
        return new SearchParameter("", 0, 1000, "", "id");
    }

    public class SortField {
        public String item;
        public String order; // ASC or DESC
    }
}